/* 
 * Copyright 2011 kOSMik.
 * This file is part of kOSMik.
 * 
 * kOSMik is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * kOSMik is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with kOSMik.  If not, see <http://www.gnu.org/licenses/>.
 *  
 * kOSMik:
 * Open Street Map - Editor.
 * http://code.google.com/p/swp-dv-ws2010-osm-2/
 */

package de.fuberlin.kosmik.files;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import android.os.Environment;
import android.util.Log;
import de.fuberlin.kosmik.log.Constants;

/**
 * Implementation of the FileManager.
 */
public class FileManagerImpl implements FileManager {

	private static final String APPLICATION_BASE_DIRECOTRY = "kOSMik";

	private File trackDir; // base directory of the track

	/**
	 * Constructor. Takes care of creating directory-structure.
	 * 
	 * @param trackId id of the track. This determines the name of the most
	 *            inner folder.
	 * @throws IOException if media (SD-card) not ready.
	 */
	public FileManagerImpl(long trackId) throws IOException {
		if (mediaReady().booleanValue()) {
			// get base application directory.

			final File appDir = new File(Environment.getExternalStorageDirectory(),
					APPLICATION_BASE_DIRECOTRY);

			// get directory for current track. create if necessary.
			trackDir = new File(appDir, Long.toString(trackId));
			if (!trackDir.exists() && trackDir.mkdirs()) {
				Log.d(Constants.FILEMGR,
						"CREATING TRACK DIRECTORY " + trackDir.getAbsolutePath());
			}
		} else {
			Log.d(Constants.TAG, "[FILEMANAGER] MEDIA NOT READY");
			throw new IOException("Media not ready");
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public File putFile(String filename) {
		final File retVal = new File(trackDir.getAbsolutePath(), filename);
		try {
			retVal.createNewFile();
		} catch (IOException e) {
			Log.d(Constants.TAG, "[FILEMANAGER] CANNOT CREATE NEW FILE");
		}
		Log.d(Constants.TAG, "[FILEMANAGER] CREATED NEW FILE: " + retVal.getAbsolutePath());
		return retVal;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public String getAbsoluteBasePath() {
		return trackDir.getAbsolutePath();
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public synchronized String getFilename(String baseName) {
		return baseName + "-" + Integer.toString((trackDir.list()).length + 1);
	}

	@Override
	public OutputStream getStream(String filename) throws IOException {
		OutputStream retVal = null;
		if (mediaReady().booleanValue()) {
			final File file = new File(trackDir, filename);
			if (!file.exists()) {
				try {
					file.createNewFile();
				} catch (IOException e) {
					Log.d(Constants.TAG,
							"IOException while creating new file in FileManagerImpl.getStream()");
					throw new IOException();
				}
			}
			try {
				retVal = new FileOutputStream(file);
			} catch (FileNotFoundException e) {
				Log.e(Constants.TAG, "this should never have happend: ", e);
			}
		} else {
			Log.d(Constants.TAG, "External media is not ready ...");
			throw new IOException("Media not ready");
		}

		return retVal;
	}

	/**
	 * Check if the media is writable.
	 * 
	 * @return true if media is writable.
	 */
	private Boolean mediaReady() {
		final String state = Environment.getExternalStorageState();
		final Boolean retVal = Boolean.valueOf(Environment.MEDIA_MOUNTED.equals(state));
		Log.d(Constants.TAG, "[FILEMANAGER] MEDIASTATE= " + state);
		return retVal;
	}
}
